package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.mapper.LoginMapper;
import cn.itsource.ymcc.result.JSONResult;
import cn.itsource.ymcc.service.ILoginService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.netflix.ribbon.proxy.annotation.Http;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author whale.chen
 * @since 2022-07-16
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {
    public final String Token_url="http://localhost:10040/oauth/token?client_id=%s&client_secret=%s&grant_type=password&redirect_uri=http://www.baidu.com&username=%s&password=%s";

    @Override
    public JSONResult common(Login login) {
        //非空 校验303
        //判断是否存在
        Wrapper<Login> wrapper=new EntityWrapper<>();
        wrapper.eq("username",login.getUsername());
        Login logintemp = selectOne(wrapper);
        AssertUtil.isNotNull(logintemp,"不存在这个用户呀");
        //拼接前端传递来的账号密码，等等  "error_description"
        Integer type = login.getType();
        String clientId = "website";//客户端是主站
        String clientSecret = "123";
        if(type.intValue() == 0){//客户端是后台
            clientId = "admin";
            clientSecret="123";
        }
        String url=String.format(Token_url,clientId,clientSecret,login.getUsername(),login.getPassword());
        //前端是map结构
        String sendPost = HttpUtil.sendPost(url, null);
        Map<String,Object> resutlMap= JSONObject.parseObject(sendPost,Map.class);
        if(resutlMap.containsKey("error_description")){//获取token失败
            return JSONResult.error("错了错了");
        }else {
            Integer expires_in = (Integer) resutlMap.get("expires_in");//多少毫秒后过期
            resutlMap.put("expiresTime", System.currentTimeMillis() + expires_in);
            return JSONResult.success(resutlMap);
        }
    }
}
